<template>
  <el-container>
    <!-- Header -->
    <el-header class="header">
      <el-row type="flex" justify="space-between" align="middle">
        <div class="logo">
          <img src="../../assets/images/logo.png" alt="Logo" />
          岳麓书院知识图谱
        </div>
        <el-menu
          :default-active="activeMenu"
          mode="horizontal"
          @select="horizontal"
          class="nav-menu"
        >
          <el-menu-item index="home">主页</el-menu-item>
          <el-menu-item index="people">人物</el-menu-item>
          <el-menu-item index="place">地点</el-menu-item>
          <el-menu-item index="building">建筑</el-menu-item>
          <el-menu-item index="concept">概念</el-menu-item>
          <el-menu-item index="event">事件</el-menu-item>
          <el-menu-item index="artifact">文物</el-menu-item>
          <el-menu-item index="period">年代</el-menu-item>
        </el-menu>
        <el-dropdown>
          <span class="el-dropdown-link">
            {{ userInfo.username
            }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <!-- <el-dropdown-menu>
            <el-dropdown-item>个人信息</el-dropdown-item>
            <el-dropdown-item>退出登录</el-dropdown-item>
          </el-dropdown-menu> -->
        </el-dropdown>
      </el-row>
    </el-header>

    <el-container>
      <!-- Aside Sidebar -->
      <el-aside width="200px" class="aside">
        <div class="profile">
          <el-avatar size="large" :src="userInfo.avatar"></el-avatar>
          <p>{{ userInfo.username }}</p>
        </div>
        <el-menu
          :default-active="activeSubMenu"
          mode="vertical"
          @select="handleAsideSelect"
        >
          <el-menu-item index="user-sys-info">用户反馈信息</el-menu-item>
          <el-menu-item index="sys-info">系统消息</el-menu-item>
          <el-menu-item index="feedback">提供反馈</el-menu-item>
          <el-menu-item index="edit-info">编辑信息</el-menu-item>
          <el-menu-item index="check-history">检索历史</el-menu-item>
        </el-menu>
      </el-aside>

      <!-- Main Content -->
      <el-main class="main">
        <div v-if="selectedSection === 'user-sys-info'">
          <!-- System Messages Section -->
          <div class="content-header">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="未读" name="unread"></el-tab-pane>
              <el-tab-pane label="已读" name="read"></el-tab-pane>
              <el-tab-pane label="全部" name="all"></el-tab-pane>
            </el-tabs>
            <div class="actions">
              <el-button @click="markSelectedRead">标记已读</el-button>
              <el-button @click="markAllRead">全部已读</el-button>
              <el-button type="danger" @click="deleteAllMessages"
                >全部删除</el-button
              >
            </div>
          </div>

          <el-table :data="paginatedMessages" style="width: 100%">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="title" label="消息主题"></el-table-column>
            <el-table-column prop="author" label="发布者"></el-table-column>
            <el-table-column prop="date" label="发布时间"></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="text" @click="viewMessage(scope.row)"
                  >查看</el-button
                >
                <el-button type="text" @click="deleteMessage(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalMessages"
          >
          </el-pagination>
        </div>
        <div v-if="selectedSection === 'sys-info'">
          <!-- System Messages Section -->
          <div class="content-header">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="未读" name="unread"></el-tab-pane>
              <el-tab-pane label="已读" name="read"></el-tab-pane>
              <el-tab-pane label="全部" name="all"></el-tab-pane>
            </el-tabs>
            <div class="actions">
              <el-button @click="markSelectedRead">标记已读</el-button>
              <el-button @click="markAllRead">全部已读</el-button>
              <el-button type="danger" @click="deleteAllMessages"
                >全部删除</el-button
              >
            </div>
          </div>

          <el-table :data="paginatedMessages" style="width: 100%">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="title" label="消息主题"></el-table-column>
            <el-table-column prop="author" label="发布者"></el-table-column>
            <el-table-column prop="date" label="发布时间"></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button type="text" @click="viewMessage(scope.row)"
                  >查看</el-button
                >
                <el-button type="text" @click="deleteMessage(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalMessages"
          >
          </el-pagination>
        </div>

        <div v-else-if="selectedSection === 'feedback'">
          <!-- Feedback Section -->
          <h2>提供反馈</h2>
          <p>在此处提供反馈表单或相关内容。</p>
        </div>

        <div v-else-if="selectedSection === 'edit-info'" class="edit-info">
          <!-- <h2>编辑信息</h2> -->
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="user-avatar">
                <el-avatar :size="120" :src="userInfo.avatar">
                  <img
                    src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                  />
                </el-avatar>
                <el-button
                  class="mt-4"
                  type="primary"
                  @click="showAvatarUpload = true"
                  >点击修改头像</el-button
                >
              </div>
              <div class="user-actions">
                <el-button style="display: none">隐藏</el-button>
                <!-- 第一个 button 会多出一截，因此加上面那个按钮将其隐藏 -->
                <el-button @click="showPasswordChange = true"
                  >修改密码</el-button
                >
                <el-button @click="showPhoneChange = true"
                  >修改手机号</el-button
                >
                <el-button @click="showUsernameChange = true"
                  >修改用户名</el-button
                >
                <el-button type="danger" @click="logout">退出登录</el-button>
              </div>
            </el-col>
            <el-col :span="16">
              <el-form
                :model="userInfo"
                label-width="100px"
                class="user-info-form"
              >
                <el-form-item label="用户名">
                  <el-input v-model="userInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="性别">
                  <el-input v-model="userInfo.gender" disabled></el-input>
                </el-form-item>
                <el-form-item label="账号">
                  <el-input v-model="userInfo.account" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                  <el-input v-model="userInfo.phone" disabled></el-input>
                </el-form-item>
                <el-form-item label="注册时间">
                  <el-input v-model="userInfo.createTime" disabled></el-input>
                </el-form-item>
                <el-form-item label="用户类型">
                  <el-input v-model="userInfo.userType" disabled></el-input>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>

          <!-- 更换头像 -->
          <el-dialog v-model="showAvatarUpload" title="修改头像" width="30%">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="userInfo.avatar"
                :src="userInfo.avatar"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-dialog>

          <!-- 修改密码 -->
          <el-dialog v-model="showPasswordChange" title="修改密码" width="30%">
            <el-form
              :model="passwordForm"
              label-width="100px"
              :rules="rules"
              ref="passwordFormRef"
            >
              <el-form-item label="验证码" prop="captcha">
                <el-input
                  v-model="passwordForm.captcha"
                  placeholder="请输入验证码"
                >
                  <template #append>
                    <el-button @click="sendCaptcha('password')"
                      >获取验证码</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="password">
                <el-input
                  v-model="passwordForm.password"
                  type="password"
                  placeholder="请输入新密码"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认新密码" prop="rePassword">
                <el-input
                  v-model="passwordForm.rePassword"
                  type="password"
                  placeholder="请再次输入新密码"
                ></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showPasswordChange = false">取消</el-button>
                <el-button type="primary" @click="changePassword"
                  >确认修改</el-button
                >
              </span>
            </template>
          </el-dialog>

          <!-- 更换手机号 -->
          <el-dialog v-model="showPhoneChange" title="修改手机号" width="30%">
            <el-form
              :model="phoneForm"
              label-width="120px"
              :rules="rules"
              ref="phoneFormRef"
            >
              <el-form-item label="旧手机验证码" prop="captcha">
                <el-input
                  v-model="phoneForm.oldCaptcha"
                  placeholder="请输入验证码"
                >
                  <template #append>
                    <el-button @click="sendCaptcha('old')"
                      >获取验证码</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="新手机号" prop="phone">
                <el-input
                  v-model="phoneForm.newPhone"
                  placeholder="请输入新手机号"
                ></el-input>
              </el-form-item>
              <el-form-item label="新手机验证码" prop="captcha">
                <el-input
                  v-model="phoneForm.newCaptcha"
                  placeholder="请输入验证码"
                >
                  <template #append>
                    <el-button @click="sendCaptcha('new')"
                      >获取验证码</el-button
                    >
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showPhoneChange = false">取消</el-button>
                <el-button type="primary" @click="changePhone"
                  >确认修改</el-button
                >
              </span>
            </template>
          </el-dialog>

          <!-- 更改用户名 -->
          <el-dialog
            v-model="showUsernameChange"
            title="修改用户名"
            width="30%"
          >
            <el-form
              :model="usernameForm"
              label-width="100px"
              :rules="rules"
              ref="usernameFormRef"
            >
              <el-form-item label="新用户名" prop="username">
                <el-input
                  v-model="usernameForm.username"
                  placeholder="请输入新用户名"
                ></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-select
                  v-model="usernameForm.gender"
                  placeholder="请选择性别"
                >
                  <el-option label="男" value="male"></el-option>
                  <el-option label="女" value="female"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showUsernameChange = false">取消</el-button>
                <el-button type="primary" @click="changeUsername"
                  >确认修改</el-button
                >
              </span>
            </template>
          </el-dialog>
        </div>

        <div v-else-if="selectedSection === 'check-history'">
          <!-- Check History Section -->
          <h2>检索历史</h2>
          <p>在此处显示历史记录。</p>
        </div>
      </el-main>
    </el-container>
  </el-container>
  <el-dialog
    class="myDialog"
    title="部分人物信息出现错误"
    v-model="dialogVisibleView"
    width="50%"
  >
    <div class="downs">
      <div class="downsBut">
        反馈图片1.JPG<svg
          t="1730391157299"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="4285"
          width="15"
          height="15"
        >
          <path
            d="M921.84736468 997.93033544H101.54506534c-24.68943392 0-44.71162586-20.00838352-44.71162584-44.71162585V631.455181c0-24.70324234 20.02219194-44.71162586 44.71162584-44.71162585s44.71162586 20.00838352 44.71162586 44.71162585v277.05190275h730.87904765V631.455181c0-24.70324234 20.02219194-44.71162586 44.71162583-44.71162585 24.68943392 0 44.71162586 20.00838352 44.71162586 44.71162585V953.21870959c0 24.70324234-20.02219194 44.71162586-44.71162586 44.71162585z"
            fill="#8a8a8a"
            p-id="4286"
          ></path>
          <path
            d="M511.69621502 839.9897621c-24.68943392 0-44.71162586-20.00838352-44.71162585-44.71162585V70.54383027c0-24.70324234 20.02219194-44.71162586 44.71162585-44.71162586s44.71162586 20.00838352 44.71162585 44.71162586v724.73430598c0 24.70324234-20.02219194 44.71162586-44.71162585 44.71162585z"
            fill="#8a8a8a"
            p-id="4287"
          ></path>
          <path
            d="M511.69621502 869.73307344c-14.37455297 0-27.92060144-6.93182094-36.30230524-18.61373431L323.62569491 639.87831001c-14.41597819-20.04980875-9.84539506-47.998027 10.21822209-62.41400518 20.02219194-14.37455297 47.94279339-9.85920347 62.3863884 10.21822208l115.47971803 160.70225499 115.45210121-160.68844659c14.443595-20.09123397 42.37800485-24.60658347 62.38638839-10.23203048 20.04980875 14.41597819 24.62039188 42.33657964 10.21822208 62.40019679l-151.75440644 211.2272207a44.65639221 44.65639221 0 0 1-36.31611365 18.64135112z"
            fill="#8a8a8a"
            p-id="4288"
          ></path>
        </svg>
      </div>
      <div class="downsBut">
        反馈文件1.DOCX<svg
          t="1730391157299"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="4285"
          width="15"
          height="15"
        >
          <path
            d="M921.84736468 997.93033544H101.54506534c-24.68943392 0-44.71162586-20.00838352-44.71162584-44.71162585V631.455181c0-24.70324234 20.02219194-44.71162586 44.71162584-44.71162585s44.71162586 20.00838352 44.71162586 44.71162585v277.05190275h730.87904765V631.455181c0-24.70324234 20.02219194-44.71162586 44.71162583-44.71162585 24.68943392 0 44.71162586 20.00838352 44.71162586 44.71162585V953.21870959c0 24.70324234-20.02219194 44.71162586-44.71162586 44.71162585z"
            fill="#8a8a8a"
            p-id="4286"
          ></path>
          <path
            d="M511.69621502 839.9897621c-24.68943392 0-44.71162586-20.00838352-44.71162585-44.71162585V70.54383027c0-24.70324234 20.02219194-44.71162586 44.71162585-44.71162586s44.71162586 20.00838352 44.71162585 44.71162586v724.73430598c0 24.70324234-20.02219194 44.71162586-44.71162585 44.71162585z"
            fill="#8a8a8a"
            p-id="4287"
          ></path>
          <path
            d="M511.69621502 869.73307344c-14.37455297 0-27.92060144-6.93182094-36.30230524-18.61373431L323.62569491 639.87831001c-14.41597819-20.04980875-9.84539506-47.998027 10.21822209-62.41400518 20.02219194-14.37455297 47.94279339-9.85920347 62.3863884 10.21822208l115.47971803 160.70225499 115.45210121-160.68844659c14.443595-20.09123397 42.37800485-24.60658347 62.38638839-10.23203048 20.04980875 14.41597819 24.62039188 42.33657964 10.21822208 62.40019679l-151.75440644 211.2272207a44.65639221 44.65639221 0 0 1-36.31611365 18.64135112z"
            fill="#8a8a8a"
            p-id="4288"
          ></path>
        </svg>
      </div>
    </div>
    <div class="ceners">
      <!-- <pre class="ppp"
        >{{ popupTips }}
 </pre
      > -->
      <div v-html="popupTips"></div>
    </div>
    <div class="dialog-footer">
      <div class="f1"></div>
      <el-button @click="dialogVisibleView = false">不采纳</el-button>
      <el-button type="primary" @click="dialogVisibleView = false"
        >采纳</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, reactive } from "vue";
import myImage from "@/assets/images/user-avatar.png";
import { HORIZONTAL } from "element-plus/es/components/virtual-list/src/defaults.mjs";
import { ElMessage, ElMessageBox, ElDialog, ElButton } from "element-plus";
import { getCaptcha, modifyUserName, userLogout } from "../../api/user";
import { tokenStore } from "../../store/token";
import { userInfoStore } from "../../store/userInfo";

const activeMenu = ref("home");
const activeSubMenu = ref("sys-info");
const activeTab = ref("unread");
const selectedRows = ref([]);

const unreadMessages = ref([
  {
    title: "发布了一个系统通知",
    author: "管理员007",
    date: "2024-10-11 12:32:23",
    content: `&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这是正文文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

是正文是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这是正文文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

是正文是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这是正文文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

是正文是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;这是正文文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

是正文是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这

文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文

这是正文这是正文这是正文这是正文这是正文这是正文这是正文这是正文<br/>`,
  },
  {
    title: "发布了一个系统通知",
    author: "管理员007",
    date: "2024-10-11 12:32:23",
    content: `这是正文文2`,
  },
]);
const readMessages = ref([
  { title: "之前的已读通知", author: "管理员001", date: "2024-09-01 10:15:23" },
]);
const popupTips = ref("");
// Track the selected section
const selectedSection = ref("sys-info");

//
const currentPage = ref(1);
const pageSize = ref(10);

const totalMessages = computed(() => {
  if (activeTab.value === "unread") return unreadMessages.value.length;
  if (activeTab.value === "read") return readMessages.value.length;
  return unreadMessages.value.length + readMessages.value.length;
});

const paginatedMessages = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredMessages.value.slice(start, end);
});

const filteredMessages = computed(() => {
  if (activeTab.value === "unread") return unreadMessages.value;
  if (activeTab.value === "read") return readMessages.value;
  return [...unreadMessages.value, ...readMessages.value];
});

const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

const markSelectedRead = () => {
  if (selectedRows.value.length > 0) {
    selectedRows.value.forEach((row) => {
      row.isRead = 1; // 标记为已读
      const index = unreadMessages.value.indexOf(row);
      if (index !== -1) {
        unreadMessages.value.splice(index, 1);
        readMessages.value.push(row);
      }
    });
    selectedRows.value = []; // 清空选中行
  }
};

const markAllRead = () => {
  unreadMessages.value.forEach((message) => {
    message.isRead = 1;
  });
  readMessages.value = [...readMessages.value, ...unreadMessages.value];
  unreadMessages.value = [];
};

const deleteAllMessages = () => {
  unreadMessages.value = [];
  readMessages.value = [];
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// Handle aside menu selection
const handleAsideSelect = (key) => {
  selectedSection.value = key;
};

const viewMessage = (row) => {
  console.log("查看消息:342", row);
  popupTips.value = row.content;
  dialogVisibleView.value = true;
};

const deleteMessage = (row) => {
  console.log("删除消息:", row);
  const indexUnread = unreadMessages.value.indexOf(row);
  if (indexUnread !== -1) {
    unreadMessages.value.splice(indexUnread, 1);
  } else {
    const indexRead = readMessages.value.indexOf(row);
    if (indexRead !== -1) {
      readMessages.value.splice(indexRead, 1);
    }
  }
};

//编辑信息

const userInfo = reactive({
  username: "小帅handsome",
  gender: "男",
  account: "2205585421",
  phone: "19982683225",
  createTime: "2024-10-3",
  userType: "普通用户",
  avatar: myImage,
});

const showAvatarUpload = ref(false);
const showPasswordChange = ref(false);
const showPhoneChange = ref(false);
const showUsernameChange = ref(false);

// 修改密码框
const passwordForm = ref({
  captcha: "",
  password: "",
  rePassword: "",
});
const passwordFormRef = ref(null);

// 修改手机号框
const phoneForm = ref({
  oldCaptcha: "",
  newPhone: "",
  newCaptcha: "",
});
const phoneFormRef = ref(null);

// 修改用户名框
const usernameForm = ref({
  username: "",
  gender: "",
});
const usernameFormRef = ref(null);

// 获取userInfoStore中的数据
const userInfoStore1 = userInfoStore();

// 正则规则
const rules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,10}$/,
      message: "密码必须是6-10位，包含大小写字母和数字",
      trigger: "blur",
    },
  ],
  rePassword: [{ required: true, message: "请再次输入密码", trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,10}$/,
      message: "用户名只能包含中文、字母、数字，长度1-10",
      trigger: "blur",
    },
  ],
};

const handleAvatarSuccess = (res, file) => {
  userInfo.avatar = URL.createObjectURL(file.raw);
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传头像图片只能是 JPG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 发送验证码
const sendCaptcha = async (type) => {
  if (type === "password") {
    if (!passwordForm.value.phone) {
      ElMessage.error("请先输入手机号");
      return;
    }
    const response = await getCaptcha(passwordForm.value.phone);
    if (response.data.code === 1) {
      ElMessage.success("验证码已发送，请耐心等待");
    }
  } else if (type === "old") {
    const response = await getCaptcha(userInfo.phone);
    if (response.data.code === 1) {
      ElMessage.success("验证码已发送，请耐心等待");
    }
  } else if (type === "new") {
    if (!phoneForm.value.newPhone) {
      ElMessage.error("请先输入手机号");
      return;
    }
    const response = await getCaptcha(phoneForm.value.newPhone);
    if (response.data.code === 1) {
      ElMessage.success("验证码已发送，请耐心等待");
    }
  }
};

// 修改密码
const changePassword = async () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      if (passwordForm.value.password !== passwordForm.value.rePassword) {
        ElMessage.error("两次密码输入不一致。");
        return;
      }
      const response = await modifyPassword({
        phone: userInfo.phone,
        password: passwordForm.value.password,
        rePassword: passwordForm.value.rePassword,
        captcha: passwordForm.value.captcha,
      });
      if (response.data.code === 1) {
        ElMessage.success("密码修改成功！");
        showPasswordChange.value = false;
      }
    } else {
      ElMessage.error("请正确填写表单。");
    }
  });
};

// 修改手机号
const changePhone = async () => {
  phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      const response = await modifyPhone({
        oldPhone: userInfo.phone,
        oldCaptcha: phoneForm.value.oldCaptcha,
        newPhone: phoneForm.value.newPhone,
        newCaptcha: phoneForm.value.newCaptcha,
      });
      if (response.data.code === 1) {
        ElMessage.success("手机号码修改成功！");
        showPhoneChange.value = false;
        userInfo.phone = phoneForm.value.newPhone;
      }
    } else {
      ElMessage.error("请正确填写表单。");
    }
  });
};

// 修改用户名
const changeUsername = async () => {
  usernameFormRef.value.validate(async (valid) => {
    if (valid) {
      const response = await modifyUserName({
        username: usernameForm.value.username,
        gender: usernameForm.value.gender,
      });
      if (response.data.code === 1) {
        ElMessage.success("用户名修改成功！");
        showUsernameChange.value = false;
        userInfo.account = usernameForm.username;
        userInfo.gender = usernameForm.gender === "男" ? 0 : 1;
      }
    } else {
      ElMessage.error("请正确填写表单。");
    }
  });
};

// 退出登录
const logout = async () => {
  ElMessageBox.confirm("是否确定退出登录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 用户点击了确定，执行退出登录操作
      const res = await userLogout();
      if (res.data.code === 1) {
        ElMessage.success("账号已退出");
        // 清空Store
        tokenStore().removeToken();
        userInfoStore().removeInfo();
      } else {
        ElMessage.error("退出登录失败");
      }
    })
    .catch(() => {
      // 用户点击了取消，显示取消消息
      ElMessage.info("已取消退出");
    });
};

const userTypeArr = ["管理员", "高级用户", "普通用户"];
// 获取用户信息，直接从store中获取
const getUserInfo = () => {
  (userInfo.username = userInfoStore1.username),
    (userInfo.gender = userInfoStore1.gender === 0 ? "男" : "女"),
    (userInfo.account = userInfoStore1.id),
    (userInfo.phone = userInfoStore1.phone),
    (userInfo.createTime = userInfoStore1.createTime);
  userInfo.userType = userTypeArr[userInfoStore1.status];
};

const dialogVisibleView = ref(false);
</script>

<style scoped>
.logo {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.logo img {
  width: 40px;
  margin-right: 10px;
}

.profile {
  text-align: center;
  padding: 20px 0;
}

.profile p {
  margin-top: 10px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.actions {
  display: flex;
  gap: 10px;
}

.header {
  border-bottom: 1px solid #dcdfe6;
}

.nav-menu {
  display: flex;
  justify-content: center;
}

.nav-menu .el-menu-item {
  padding: 0 40px;
}

.aside {
  border-right: 1px solid #dcdfe6;
}

.main {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.edit-info {
  padding: 20px;
  align-content: center;
}

.user-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.user-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.user-actions .el-button {
  width: auto;
}

.user-info-form {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input.is-disabled .el-input__inner {
  color: #606266;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.mt-4 {
  margin-top: 1rem;
}
.downsBut {
  padding: 5px 12px;
  border: 1px solid #aaa;
  border-radius: 6px;
  margin-right: 30px;
  cursor: pointer;
  user-select: none;
}
.downs {
  display: flex;
  align-items: center;
  border-top: 1px solid #ccc;
  padding-top: 20px;
}
.ceners {
  background-color: #fff;
  padding: 20px;
  word-break: break-all !important;
  max-height: 42vh;
  overflow: hidden auto;
  margin: 20px 0;
}
.dialog-footer {
  display: flex;
}
.f1 {
  flex: 1;
}
</style>
